package org.ewancle.springboothivehdfs.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "hive")
public class HiveConfig {
    private Jdbc jdbc;
    private Auth auth;
    private Kerberos kerberos;

    @Data
    public static class Jdbc {
        private String url;
        private String driverClassName;
    }

    @Data
    public static class Auth {
        private String mode;
        private String username;
        private String password;
    }

    @Data
    public static class Kerberos {
        private String principal;
        private String keytabPath;
    }

    @Bean
    public DataSource hiveDataSource() throws SQLException {
        String url = jdbc.getUrl();
        Properties properties = new Properties();

        if ("kerberos".equalsIgnoreCase(auth.getMode())) {
            // Kerberos 认证
            log.info("Using Kerberos authentication for Hive");
            System.setProperty("java.security.krb5.conf", "/etc/krb5.conf");

            // 配置 Kerberos 认证
            url = url + ";principal=" + kerberos.getPrincipal();
            properties.setProperty("hadoop.security.authentication", "kerberos");
        } else {
            // 用户名密码认证
            log.info("Using simple authentication for Hive with user: {}", auth.getUsername());
            properties.setProperty("user", auth.getUsername());
            properties.setProperty("password", auth.getPassword());
        }

        // 使用连接池创建数据源
        /*return ConnectionPoolUtil.createHikariDataSource(
                jdbc.getDriverClassName(),
                url,
                properties,
                10  // 连接池大小
        );*/
        // 步骤1：创建Hikari配置对象
        HikariConfig config = new HikariConfig();
        // 步骤2：设置JDBC URL
        config.setJdbcUrl("jdbc:hive2://localhost:10000/default");
        // 步骤3：设置用户名和密码
        config.setUsername("your_username");
        config.setPassword("your_password");
        // 步骤4：设置连接池大小
        config.setMaximumPoolSize(10);
        // 步骤5：创建Hikari连接池
        return new HikariDataSource(config);
    }
}
